package com.nuoniu.sibanyun.controller.pay;

import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.entity.crm.CrmGoodsOrder;
import com.nuoniu.sibanyun.entity.expenses.ExpensesPaymentOrder;
import com.nuoniu.sibanyun.service.crm.ICrmGoodsOrderService;
import com.nuoniu.sibanyun.service.expenses.IExpensesPaymentOrderService;
import com.nuoniu.sibanyun.service.redis.RedisService;
import com.nuoniu.sibanyun.utils.QRCodeGeneratorUtil;
import com.nuoniu.sibanyun.utils.WeXinUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 微信支付
 * @auther 小啊刚
 * @date 2020-07-22
 */
@RestController
@Api(value = "微信支付", tags = "微信支付")
public class WeXinPayController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private ICrmGoodsOrderService orderService;
    @Autowired
    private IExpensesPaymentOrderService paymentOrderService;

    /**
     * 微信公众号签名
     * @author 小啊刚
     * @date 2020-08-21
     */
    @GetMapping("weXin/getSignature")
    public HttpResult getSignature(String url) {
        String accessToken;
        if(redisService.hasKey("access_token") && redisService.get("access_token") != null) {
            accessToken = redisService.get("access_token").toString();
        }else {
            accessToken = WeXinUtils.getAccessToken();
            redisService.set("access_token", accessToken, 7190);
        }
        Map data = WeXinUtils.JsapiTicket(accessToken, url);
        return HttpResult.ok(data);
    }

    /**
     * PC发起微信支付
     * @author 小啊刚
     * @date 2020-08-21
     */
    @ApiOperation("PC发起微信支付")
    @GetMapping("sby/weXin/pay")
    public HttpResult pay(String orderId, String totalFee, String outTradeNo) {
        WeXinUtils myWXPayUtil = new WeXinUtils();
        CrmGoodsOrder order = orderService.getById(orderId);
        Map result = myWXPayUtil.createNative(order);
        System.out.println(result.get("code_url"));
        String qrCode = QRCodeGeneratorUtil.getQRCodeImage(result.get("code_url").toString(), 360, 360);
        return HttpResult.ok("OK", "data:image/jpg;base64," + qrCode);
    }

    /**
     * PC发起微信支付-支付订单
     * @param orderId
     * @return
     */
    @ApiOperation("PC发起微信支付-支付订单")
    @GetMapping("sby/weXin/payFormPayOrder")
    public HttpResult payFormPayOrder(String orderId) {
        WeXinUtils myWXPayUtil = new WeXinUtils();
        ExpensesPaymentOrder paymentOrder = paymentOrderService.getById(orderId);
        Map result = myWXPayUtil.createNativeFormPayOrder(paymentOrder);
        System.out.println(result.get("code_url"));
        String qrCode = QRCodeGeneratorUtil.getQRCodeImage(result.get("code_url").toString(), 360, 360);
        return HttpResult.ok("OK", "data:image/jpg;base64," + qrCode);
    }

}
